package com.qf.blog.controller.web;

import com.alibaba.fastjson.JSON;
import com.qf.blog.core.constants.BaseConstants;
import com.qf.blog.core.servlet.BaseServlet;
import com.qf.blog.core.utils.EmailUtils;
import com.qf.blog.core.utils.PasswordUtils;
import com.qf.blog.core.utils.UUIDUtils;
import com.qf.blog.dto.EmailDto;
import com.qf.blog.entity.UserEntity;
import com.qf.blog.service.IUserService;
import com.qf.blog.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import java.util.Date;

@WebServlet("/UserServlet/*")
public class UserServlet extends BaseServlet {

    private IUserService userService = new UserServiceImpl();

    public String register() throws Exception {
        String s = req.getReader().readLine();
        UserEntity userEntity = JSON.parseObject(s, UserEntity.class);

        // 1.判断当前邮箱或者用户名是否已经被注册了(去数据库根据用户名或者邮箱查询一下)

        // 2.调用业务层的注册方法
        userService.register(userEntity);
        String activationCode = userEntity.getActivationCode();

        // 3.给用户的邮箱发送激活账号的连接
        EmailDto emailDto = new EmailDto();
        emailDto.setTilte("Blog新用户注册账号激活");
        emailDto.setToUser(userEntity.getEmail());
        emailDto.setContent("<a href = 'http://127.0.0.1:8080/UserServlet/activation?code=" + activationCode + "'>点击这里激活</a>");
        EmailUtils.sendEmailInfoUser(emailDto);

        // 4.提示用户
        return outJson(true);
    }

    // 激活哪个账号？
    public String activation() throws Exception {

        // 1.获取激活码
        String activationCode = req.getParameter("code");
        System.out.println("激活码:" + activationCode);

        // 2.验证
        UserEntity userEntity = userService.byActivationCode(activationCode);
        if (userEntity == null) {
            System.out.println("激活码有误");
            return BaseConstants.BASE_SCRIPT + ":激活码有误";
        } else {
            userEntity.setStatus(2);
            userService.update(userEntity);
            return BaseConstants.BASE_REDIRECT + ":PageServlet/view/site/login.html";
        }
    }

    public String login() throws Exception {
        String s = req.getReader().readLine();
        UserEntity userEntity = JSON.parseObject(s, UserEntity.class);
        userEntity = userService.login(userEntity.getUsername(), userEntity.getPassword());

        // 判断认证成功
        if (userEntity == null) {
            return outJson(100, "用户名获密码错误1");
        }

        // 登录成功
        userEntity.setPassword(null); // 把密码设置为null，然哎放到session中
        req.getSession().setAttribute("loginUser", userEntity);
        return outJson(200, "登录成功");
    }
}
